#include<bits/stdc++.h>
using namespace std;

// 【题目】力扣1944. 队列中可以看到的人数
// 【难度】困难
// 【提交】https://leetcode.cn/problems/number-of-visible-people-in-a-queue/submissions/664796439/
// 【标签】栈；数组；单调栈
class Solution {
public:
    vector<int> canSeePersonsCount(vector<int>& heights) {
        int n = heights.size();
        vector<int> stack;
        vector<int> res(n, 0);

        for (int i = n - 1; i >= 0; i--) {
            int h = heights[i];
            while (!stack.empty() && stack.back() < h) {
                stack.pop_back();
                res[i]++;
            }
            if (!stack.empty()) {
                res[i]++;
            }
            stack.push_back(h);
        }
        return res;
    }
};